import pygame
import os
import sys
import numpy
import wave
import struct
import math

def create_directory(path):
    """创建目录（如果不存在）"""
    if not os.path.exists(path):
        os.makedirs(path)

def generate_simple_background(width, height, color, text=""):
    """生成简单的背景图片"""
    surface = pygame.Surface((width, height))
    surface.fill(color)
    if text:
        font = pygame.font.Font(None, 72)
        text_surface = font.render(text, True, (255, 255, 255))
        text_rect = text_surface.get_rect(center=(width/2, height/2))
        surface.blit(text_surface, text_rect)
    return surface

def generate_simple_card(width, height, color, name=""):
    """生成简单的卡牌图片"""
    surface = pygame.Surface((width, height))
    surface.fill(color)
    if name:
        font = pygame.font.Font(None, 36)
        text_surface = font.render(name, True, (0, 0, 0))
        text_rect = text_surface.get_rect(center=(width/2, height/2))
        surface.blit(text_surface, text_rect)
    return surface

def generate_character(width, height, color, name=""):
    """生成简单的角色图片"""
    surface = pygame.Surface((width, height))
    surface.fill(color)
    pygame.draw.circle(surface, (255, 255, 255), (width//2, height//3), min(width, height)//4)
    if name:
        font = pygame.font.Font(None, 36)
        text_surface = font.render(name, True, (255, 255, 255))
        text_rect = text_surface.get_rect(center=(width/2, height*2/3))
        surface.blit(text_surface, text_rect)
    return surface

def generate_simple_sound(frequency, duration):
    """生成简单的音效"""
    # 音频参数
    sample_rate = 44100  # 采样率
    amplitude = 32767    # 振幅
    
    # 生成音频数据
    num_samples = int(duration * sample_rate)
    sound_data = []
    for i in range(num_samples):
        t = float(i) / sample_rate
        # 生成一个简单的正弦波
        value = int(amplitude * math.sin(2 * math.pi * frequency * t))
        # 添加左右声道
        sound_data.append(struct.pack('h', value))
        sound_data.append(struct.pack('h', value))
    
    return b''.join(sound_data)

def save_wave_file(filename, sound_data):
    """保存为WAV文件"""
    with wave.open(filename, 'wb') as wave_file:
        # 设置参数 (声道数, 采样宽度, 采样率, 采样点数, 压缩类型, 压缩名称)
        wave_file.setparams((2, 2, 44100, 0, 'NONE', 'not compressed'))
        wave_file.writeframes(sound_data)

def generate_enemy(width, height, color, name=""):
    """生成敌人图像"""
    surface = pygame.Surface((width, height))
    surface.fill((0, 0, 0, 0))  # 透明背景
    
    # 绘制敌人基本形状
    if "史莱姆" in name:
        # 绘制史莱姆形状
        pygame.draw.ellipse(surface, color, (10, height//3, width-20, height//2))
        pygame.draw.ellipse(surface, (255, 255, 255), (width//3, height//3, 10, 10))  # 眼睛
    elif "骷髅" in name:
        # 绘制骷髅形状
        pygame.draw.circle(surface, color, (width//2, height//3), width//4)  # 头
        pygame.draw.rect(surface, color, (width//3, height//2, width//3, height//3))  # 身体
    
    return surface

def generate_card_image(width, height, card_type, name=""):
    """生成卡牌图片"""
    surface = pygame.Surface((width, height), pygame.SRCALPHA)
    
    # 根据卡牌类型设置颜色
    colors = {
        'attack': (200, 50, 50),
        'defense': (50, 50, 200),
        'skill': (50, 200, 50)
    }
    base_color = colors.get(card_type, (200, 200, 200))
    
    # 绘制卡牌背景
    pygame.draw.rect(surface, base_color, (0, 0, width, height), border_radius=10)
    
    # 添加卡牌花纹
    for i in range(3):
        pygame.draw.rect(surface, (255, 255, 255, 50), 
                        (10 + i*5, 10 + i*5, width-20-i*10, height-20-i*10), 1)
    
    # 添加卡牌图标
    icon_size = 60
    icon_surface = pygame.Surface((icon_size, icon_size), pygame.SRCALPHA)
    if card_type == 'attack':
        # 绘制剑的图标
        pygame.draw.polygon(icon_surface, (255, 255, 255), 
                          [(30, 10), (40, 20), (20, 40), (10, 30)])
    elif card_type == 'defense':
        # 绘制盾的图标
        pygame.draw.circle(icon_surface, (255, 255, 255), 
                         (icon_size//2, icon_size//2), icon_size//3)
    
    surface.blit(icon_surface, (width//2 - icon_size//2, height//3 - icon_size//2))
    
    return surface

def generate_resources():
    """生成所有游戏资源"""
    pygame.init()
    
    # 获取项目根目录的绝对路径
    current_dir = os.path.dirname(os.path.abspath(__file__))
    base_dir = os.path.join(os.path.dirname(current_dir), 'assets')
    print(f"Creating resources in: {base_dir}")
    
    # 创建资源目录
    dirs = ['backgrounds', 'cards', 'characters', 'fonts', 'sounds', 'music']
    for dir_name in dirs:
        dir_path = os.path.join(base_dir, dir_name)
        create_directory(dir_path)
        print(f"Created directory: {dir_path}")
    
    # 复制默认中文字体到fonts目录
    default_font_path = os.path.join(base_dir, 'fonts', 'simhei.ttf')
    if not os.path.exists(default_font_path):
        # 这里使用系统自带的黑体字体
        system_font_path = {
            'windows': 'C:/Windows/Fonts/simhei.ttf',
            'darwin': '/System/Library/Fonts/PingFang.ttc',  # macOS
            'linux': '/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf'  # Linux
        }.get(sys.platform)
        
        if system_font_path and os.path.exists(system_font_path):
            import shutil
            shutil.copy2(system_font_path, default_font_path)
            print(f"Copied system font to: {default_font_path}")
        else:
            print("Warning: Could not find system Chinese font")
    
    # 生成背景
    backgrounds = {
        'title': generate_simple_background(1280, 720, (50, 0, 100), "迷雾卡牌：深渊探险"),
        'battle': generate_simple_background(1280, 720, (0, 50, 0), "战斗场景"),
        'character_select': generate_simple_background(1280, 720, (0, 0, 50), "选择角色")
    }
    
    for name, surface in backgrounds.items():
        pygame.image.save(surface, os.path.join(base_dir, 'backgrounds', f'{name}.png'))
    
    # 生成卡牌
    cards = {
        'strike': generate_simple_card(240, 360, (200, 200, 200), "打击"),
        'defend': generate_simple_card(240, 360, (200, 200, 200), "防御")
    }
    
    for name, surface in cards.items():
        pygame.image.save(surface, os.path.join(base_dir, 'cards', f'{name}.png'))
    
    # 生成角色
    characters = {
        'warrior': generate_character(200, 300, (150, 0, 0), "战士"),
        'mage': generate_character(200, 300, (0, 0, 150), "法师")
    }
    
    for name, surface in characters.items():
        pygame.image.save(surface, os.path.join(base_dir, 'characters', f'{name}.png'))
    
    # 生成音效文件
    sounds = {
        'card_play': (220, 0.1),    # 短促的高音
        'attack': (150, 0.2),       # 较长的中音
        'damage': (100, 0.15),      # 短促的低音
        'victory': (440, 0.5),      # 较长的胜利音效
        'defeat': (110, 0.5),       # 较长的失败音效
        'button_click': (330, 0.05)  # 非常短的按钮音效
    }
    
    print("Generating sound files...")
    for name, (freq, duration) in sounds.items():
        sound_data = generate_simple_sound(freq, duration)
        filename = os.path.join(base_dir, 'sounds', f'{name}.wav')
        save_wave_file(filename, sound_data)
        print(f"Created sound file: {filename}")
    
    # 生成敌人图像
    enemies = {
        '史莱姆': generate_enemy(200, 200, (0, 255, 0), "史莱姆"),
        '骷髅战士': generate_enemy(200, 200, (200, 200, 200), "骷髅")
    }
    
    # 保存敌人图像
    enemy_dir = os.path.join(base_dir, 'enemies')
    create_directory(enemy_dir)
    for name, surface in enemies.items():
        pygame.image.save(surface, os.path.join(enemy_dir, f'{name}.png'))
    
    pygame.quit()

if __name__ == "__main__":
    generate_resources() 